@extends('layouts.admin')

@section('title', '部门管理')

@section('style')
    <link rel="stylesheet" href="{{asset('lib/zTree/v3/css/zTreeStyle/zTreeStyle.css')}}" type="text/css">
@endsection

@section('content')
    <nav class="breadcrumb"><i class="Hui-iconfont">&#xe67f;</i> 办公 <span class="c-gray en">&gt;</span> 人事管理 <span class="c-gray en">&gt;</span> 组织架构 <a class="btn btn-success radius r" style="line-height:1.6em;margin-top:3px" href="javascript:location.replace(location.href);" title="刷新" ><i class="Hui-iconfont">&#xe68f;</i></a></nav>
    <div style="position: fixed;width: 20%;top: 50px;left: 0;bottom: 0;box-sizing: border-box;border-right: 1px solid #ccc;">
        <div class="col-xs-12 col-sm-12 ml-15 mt-10">
            <div class="row cl">
                <input class="btn btn-warning radius add_department" style="width: 90%;height: 35px;" type="button" value="新增部门">
            </div>
            <div class="row cl">
                <ul id="department_tree" class="ztree"></ul>
            </div>
        </div>
    </div>
    <div style="position: fixed;width: 80%;top: 50px;right: 0;bottom: 0;box-sizing: border-box;">
        <div class="col-xs-12 col-sm-12">
            <div class="row cl">
                <div class="mt-5 ml-10 mr-10">
                    <table id="listTable" class="table table-border table-bordered table-bg table-hover">
                        <thead>
                        <tr class="text-c">
                            <th><input type="checkbox" name="checkList"/></th>
                            <th>姓名</th>
                            <th>主要部门</th>
                            <th>主要岗位</th>
                            <th>手机</th>
                            <th>微信号</th>
                            <th>账号状态</th>
                            <th>创建时间</th>
                            <th>操作</th>
                        </tr>
                        </thead>
                    </table>
                </div>
            </div>
        </div>
    </div>
@endsection
@section('script')
    <script type="text/javascript" src="{{asset('lib/zTree/v3/js/jquery.ztree.all-3.5.min.js')}}"></script>
    <script>
        var $department_tree=null;
        function refresh_department_tree(){
            $department_tree.reAsyncChildNodes(null, "refresh");
        }
        $(document).ready(function(){
            var setting = {
                view: {dblClickExpand: false, showLine: true, selectedMulti: false},
                edit: {enable: true,removeTitle: "点击删除部门", renameTitle: "点击编辑部门"},
                data: {simpleData: {enable:true, idKey: "id", pIdKey: "pId", rootPId: "-1"}},
                async: {
                    enable: true,
                    url:"{{url('personnel/department/tree_data')}}",
                    dataFilter: filter
                },
                callback: {
                    beforeEditName: beforeEditName,
                    beforeRemove: beforeRemove,
                    onClick:selectDepartMentNode
                }
            };
            function filter(treeId, parentNode, childNodes){
                if (!childNodes) return null;
                for (var i=0, l=childNodes.length; i<l; i++) {
                    if(childNodes[i].id==0){
                        childNodes[i].open=true;
                        childNodes[i].iconOpen="{{url('lib/zTree/v3/css/zTreeStyle/img/diy/1_open.png')}}";
                        childNodes[i].iconClose="{{url('lib/zTree/v3/css/zTreeStyle/img/diy/1_close.png')}}";
                    }else{
                        childNodes[i].icon="{{url('lib/zTree/v3/css/zTreeStyle/img/diy/3.png')}}";
                    }
                    childNodes[i].name = childNodes[i].name.replace(/\.n/g, '.');
                }
                return childNodes;
            }
            function beforeEditName(treeId, treeNode){
                if(treeNode.id=='0'){
                    layer_error_message('该部门不能被编辑!');
                    return false;}
                layer_full_show("编辑"+treeNode.name+"部门信息",'{{url('personnel/department/edit')}}?id='+treeNode.id);
                return false;
            }
            function beforeRemove(treeId, treeNode) {
                if(treeNode.id=='0'){
                    layer_error_message('该部门不能被删除!');
                    return false;}
                if(treeNode.children && treeNode.children.length>0){
                    layer_error_message('该部门还有子部门不能删除!');
                    return false;
                }
                var flag=confirm("确认删除" + treeNode.name + "部门吗？");
                if(flag){
                    $.ajax({
                        url: "{{url('personnel/department/delete')}}",
                        data:{id:treeNode.id},
                        async:false,
                        dataType: 'json',
                        success: function(data){
                            if(data['successFlag']==1){
                                layer_success_message('删除成功!');
                            }else{
                                layer_error_message("删除部门失败:"+data['msg']);
                                flag=false;
                            }
                        },
                        error:function(data) {
                            layer_error_message('删除失败!');
                            flag=false;
                        },
                    });
                }
                return flag;

            }
            function selectDepartMentNode(event, treeId, treeNode) {
                var selectNodeId=treeNode.id;
                if(treeNode.id=='0'){selectNodeId="";}
                if(selectNodeId==$MAIN.select_department_id){return;}
                $MAIN.select_department_id=selectNodeId;
                $MAIN.searchOnDepartmentSelect();

            };
            $department_tree=$.fn.zTree.init($("#department_tree"), setting);

            $(".add_department").click(function(){
                var parent_id=0;
                if($MAIN.select_department_id!=''){
                    parent_id=$MAIN.select_department_id;
                }
                layer_full_show("添加部门",'{{url('personnel/department/add')}}?parent_id='+parent_id);
            })
        });
    </script>
    <script>
        var $dataTable=null;
        var $MAIN={currentPage:1,StatusType:{ON_WORK:1,LOCK:2,LEAVE:3},select_department_id:"",search_time_sign:null}
        $(function(){
            $dataTable=$('#listTable').dataTable({
                "sPaginationType" : "full_numbers",
                "processing": true,
                "serverSide": true,
                "searching": false,
                "dom": '<l<\'#topPlugin\'>f>rt<ip><"clear">',
                "ajax":{
                    "url":"{{url('system/user/list')}}",
                    "type": 'post',
                    "data": function ( d ) {
                        d.name= $("#query_name").val();
                        d.major_department_id=$MAIN.select_department_id;
                        d.page=$MAIN.currentPage;
                    },
                    'dataSrc':function(result){
                        var datas=result.data;
                        if(datas){
                            for(var i=0;i<datas.length;i++){
                                datas[i].DT_RowClass='text-c';
                            }
                        }
                        return datas;
                    }
                },
                "columnDefs": [{
                    "targets": "_all",
                    "searchable":false
                },{
                    "targets": [-1,0,1,4,5],
                    "orderable":false
                }],
                "columns": [
                    {
                        "data": "id",
                        "render": function (data, type, row, meta) {
                            return '<input type="checkbox"  name="checkList" class="checkchild"  value="' + data + '" />';
                        }
                    },
                    { "data": "name"},
                    { "data": "major_department_name"},
                    { "data": "major_station_name" },
                    { "data": "phone" },
                    { "data": "wx_no" },
                    { "data": "account_status","render": function (data, type, row, meta) {
                        if(data==$MAIN.StatusType.ON_WORK){return '<span class="label label-success radius">在职</span>';}
                        if(data==$MAIN.StatusType.LOCK){return '<span class="label label-warning radius">锁定</span>';}
                        if(data==$MAIN.StatusType.LEAVE){return '<span class="label label-danger radius">离职</span>';}
                    }},
                    { "data": "created_at" },
                    { "data": "id","class":"f-14","render": function (data, type, row, meta) {
                        return '<a title="编辑" href="javascript:;" data-id="'+data+'" class="ml-5 editBtn" style="text-decoration:none"><i class="Hui-iconfont">&#xe6df;</i></a>' +
                                '<a title="删除" href="javascript:;" data-id="'+data+'" class="ml-5 delBtn" style="text-decoration:none"><i class="Hui-iconfont">&#xe6e2;</i></a>';
                    }},
                ],
                drawCallback: function( settings ) {
                    $('input[name=checkList]')[0].checked=false;
                },
                "initComplete":function(settings, json){

                    var uploadImport='<span class="btn-upload">'+
                                        '<form  method="post" class="form form-horizontal" id="import-form" enctype="multipart/form-data">'+
                                        '<a href="javascript:void();" class="btn btn-primary radius upload=btn"><i class="Hui-iconfont">&#xe645;</i>批量导入</a>'+
                                        '<input type="file" multiple="" name="file" id="file" class="input-file" style="height: 100%;width: 100%;">'+
                                        '</form>'+
                                      '</span>';
                    var topPlugin='<button class="btn btn-danger radius lockSelectBtn"><i class="Hui-iconfont">&#xe6e2;</i> 批量锁定</button> ' +
                                  '<button class="btn btn-warning radius leaveSelectBtn"><i class="Hui-iconfont">&#xe6e2;</i> 批量离职</button> '+
                                  '<button class="btn btn-primary radius addBtn" ><i class="Hui-iconfont">&#xe600;</i>新增用户</button>'+
                                  '&nbsp;'+ uploadImport+
                                  '&nbsp;<input type="text" class="input-text radius size-M" id="query_name" style="width: 200px;" placeholder="输入姓名查询">'+
                                  '&nbsp; <button type="button" class="btn btn-success radius btnSearch"><i class="Hui-iconfont">&#xe665;</i> 搜索</button>'
//                                  '<button  class="btn btn-info  btn-sm radius expCsv">导出全部</button><iframe id="exp" style="display:none;"></iframe>'
                    $("#topPlugin").append(topPlugin);
                }
            });
            $dataTable.on( 'page.dt', function () {
                var info = $dataTable.api();
                $MAIN.currentPage=parseInt(info.page())+1;
            } );
        });

        $MAIN.searchOnDepartmentSelect=function(){
            if($MAIN.search_time_sign!=null){clearTimeout($MAIN.search_time_sign)}
            $MAIN.search_time_sign=setTimeout(function(){$MAIN.search();},500);
        }
        $MAIN.search=function(){
            $dataTable.api().ajax.reload();
        }
        $MAIN.getSelectCheckBoxValue=function(){
            var theArray=[];
            $("input[name=checkList]:checked").each(function() {
                theArray.push($(this).val());
            });
            return theArray;
        }
        $MAIN.deleteData=function(id){
            layer.confirm('确定要删除该用户吗？',{
                    btn: ['确定','取消'],
                    shade: false,
                    closeBtn: 0
                },
                function(){
                    $.ajax({
                        url: "{{url('system/user/delete')}}",
                        data:{id:id},
                        dataType: 'json',
                        success: function(data){
                            if(data['successFlag']==1){
                                layer_success_message('删除成功!');
                                $MAIN.search();
                            }else{
                                layer_error_message(data['msg']);
                            }
                        },
                        error:function(data) {
                            layer_error_message('删除失败!');
                        },
                    });
                });
        }
        $MAIN.updateStatus=function(ids,statusType){
            var confirmMsg="离职";
            if(statusType==$MAIN.StatusType.LOCK){
                confirmMsg="锁定";
            }
            layer.confirm("确定要"+confirmMsg+"选择的人员吗？",{
                    btn: ['确定','取消'],
                    shade: false,
                    closeBtn: 0
                },
                function(){
                    $.ajax({
                        url: "{{url('system/user/updateStatus')}}",
                        data:{ids:ids,account_status:statusType},
                        dataType: 'json',
                        type:'post',
                        success: function(data){
                            if(data['successFlag']==1){
                                layer_success_message(confirmMsg+'操作成功!');
                                $MAIN.search();
                            }
                        },
                        error:function(data) {
                            layer_error_message(confirmMsg+'操作失败!');
                        },
                    });
                });
        }

        $(function(){
            $(document).on("click",".btnSearch",function(){
                $MAIN.search();
            });
            $(document).on("click",".lockSelectBtn",function(){
               var ids=$MAIN.getSelectCheckBoxValue();
               if(ids.length<=0){
                   layer.msg('请选择需要锁定的人员', {icon:5,time:1000});
               }else{
                   $MAIN.updateStatus(ids,$MAIN.StatusType.LOCK);
               }
            });
            $(document).on("click",".leaveSelectBtn",function(){
               var ids=$MAIN.getSelectCheckBoxValue();
               if(ids.length<=0){
                   layer.msg('请选择需要离职的人员', {icon:5,time:1000});
               }else{
                   $MAIN.updateStatus(ids,$MAIN.StatusType.LEAVE);
               }
            });
            $(document).on("click",".addBtn",function(){
                layer_full_show("添加人员",'{{url('system/user/add')}}');
            });
            $(document).on("click",".editBtn",function(){
                layer_full_show("编辑人员",'{{url('system/user/edit')}}?id='+$(this).data("id"));
            });
            $(document).on("click",".delBtn",function(){
                $MAIN.deleteData($(this).data("id"));
            });
            $(document).on("change","#file",function(){
                $("#import-form").ajaxSubmit({
                    type: 'post',
                    url: "{{url('system/user/import')}}",
                    success: function(data){
                        if(data['successFlag']==1){
                            layer_success_message("添加成功!");
                           $MAIN.search();
                        }else{
                            layer_error_message(data['msg']);
                        }
                    },
                    error: function(XmlHttpRequest, textStatus, errorThrown){
                        layer_error_message('添加失败!');
                    }
                });
                $("#import-form")[0].reset();
            });
        })
    </script>
@endsection